package com.hurl.waguji.biz.download;

import java.util.ArrayList;
import java.util.List;

import org.testng.log4testng.Logger;


import com.hurl.library.spider.UrlPattern;
import com.hurl.library.util.StringUtils;
import com.hurl.waguji.base.Formatter;
import com.hurl.waguji.base.dataprocess.ProcessParams;
import com.hurl.waguji.persistence.DmGpBO;
import com.hurl.waguji.persistence.JcsjFhrzFhbHexunBO;
import com.hurl.waguji.persistence.JcsjFhrzFhbHexunBOId;

class ProfileFhHexunProcessor extends BaseDownloadForUpdateProcessor{
	public ProfileFhHexunProcessor(ProcessParams params,
			DownloadIdentifier identifier) {
		super(params, identifier);
	}
	private static final Logger log = Logger.getLogger(ProfileFhHexunProcessor.class);

	private List<JcsjFhrzFhbHexunBO> html2BO(String gpdm, String html) {
		if(StringUtils.isBlank(html)){
			return null;
		}
		html = StringUtils.substringBetween(html, "<td class=\"lastbgcolor\"><strong>备注</strong></td>", "</table>");
		List<String> trlist = StringUtils.substringsBetween(html, "<tr>", "</tr>");
		if(trlist==null || trlist.isEmpty() || trlist.size()==1){
			return null;
		}
		List<JcsjFhrzFhbHexunBO> result = new ArrayList<JcsjFhrzFhbHexunBO>(trlist.size()-1);
		JcsjFhrzFhbHexunBO bo = null;
		for(int i=0;i<trlist.size()-1;i++){
			List<String> tdlist = StringUtils.substringsBetween(trlist.get(i), "<span class=\"font10\">", "</span>");
			bo = new JcsjFhrzFhbHexunBO();
			
			bo.setId(new JcsjFhrzFhbHexunBOId(gpdm,Formatter.toDate(tdlist.get(0))));
			bo.setMgfh(Formatter.toDouble(tdlist.get(1)));
			bo.setMgsg(Formatter.toDouble(tdlist.get(2)));
			bo.setMgzg(Formatter.toDouble(tdlist.get(3)));
			bo.setDjr(Formatter.toDate(tdlist.get(4)));
			bo.setPxed(Formatter.toDouble(tdlist.get(5)));
			bo.setCxr(Formatter.toDate(tdlist.get(6)));
			bo.setLastupdate(currentTime);
			result.add(bo);
		}
		return result;
	}
	
	@Override
	public void convertHTML2BO(String url, String html, BOSaver collector) {

		if(StringUtils.isBlank(html)){
			return;
		}

		String gpdm = context.getEnvAsString("gpdm");
		
		List<JcsjFhrzFhbHexunBO> list = html2BO(gpdm,html);
		UniqueChecker checker = UniqueChecker.getInstance();
		if(list==null || list.isEmpty())return;
		for(JcsjFhrzFhbHexunBO bo : list){
			if(checker.isUnique(bo.getId().getGpdm()+bo.getId().getGgr())){
				collector.addBO(bo);
			}else{
				log.warn("重复："+bo);
			}
		}
	
	}

	@Override
	public UrlPattern getUrlPattern() {
		return new StockIteratorUrlPattern(context) {
			
			@Override
			public String bo2url(DmGpBO bo) {
				return "http://stockdata.stock.hexun.com/2009_fhzzgb_"+bo.getGpDmJ()+".shtml";
			}
		};
	}

}
